import { MciForm, MciFormItem, MciSelect, MciSwitch } from '@/components/base';
import { Crontab } from '@/components/business/Crontab';
import FieldMapping from '@/components/business/VarMapping/index.vue';
import { IJob } from './type';
import {
  IGetTableFieldsReq,
  IGetTableFieldsRes,
  IGetTableListRes,
  IPostDecisionListWithCategoryRes,
  getAppList,
  getDecisionFlowFlowVarsBatch,
  getTableFields,
  getTableList,
  postDecisionListWithCategory,
  postJobAdd,
  postJobModify
} from '@/api';
import { IOption } from '@/components/base/Select';
import { ElTreeSelect } from 'element-plus';
import { JobDTO } from '../ExeList/type';

export const ExeAdd = defineComponent({
  name: 'ExeAdd',
  emits: ['close'],
  setup(props, { emit, expose }) {
    // 字段映射
    const mappingParam = reactive({
      isMatch: false
    });
    const fieldMappingRef = ref<any>();
    // 表单
    const timedExeFormRef = ref<any>();
    const timedExeForm = reactive<IJob>({
      id: '',
      appId: '',
      cronExpression: '',
      flowIds: [],
      fullScan: 0,
      mapping: {},
      status: 0,
      tableName: '',
      jobName: ''
    });
    // 修改回显
    let modifyFlag = false;
    let tableNameFlag = false;
    let flowIdsFlag = false;
    // 初始化
    const initData = (exeData: JobDTO) => {
      if (exeData) {
        modifyFlag = true;
        tableNameFlag = true;
        flowIdsFlag = true;
        timedExeForm.id = exeData.id;
        timedExeForm.appId = exeData.appId;
        timedExeForm.cronExpression = exeData.cronExpression || '';
        timedExeForm.flowIds = exeData.flowIds || [];
        timedExeForm.fullScan = exeData.fullScan;
        timedExeForm.mapping = exeData.mapping || {};
        timedExeForm.status = exeData.status;
        timedExeForm.tableName = exeData.tableName || '';
        timedExeForm.jobName = exeData.jobName || '';
      }
    };
    // 重置
    const resetData = () => {
      timedExeForm.id = '';
      timedExeForm.appId = '';
      timedExeForm.cronExpression = '';
      timedExeForm.flowIds = [];
      timedExeForm.fullScan = 0;
      timedExeForm.mapping = {};
      timedExeForm.status = 0;
      timedExeForm.tableName = '';
      timedExeForm.jobName = '';
      modifyFlag = false;
      tableNameFlag = false;
      flowIdsFlag = false;
    };

    // appId选项
    const appIdOptions = ref<IOption[]>([]);
    // 表选项
    const tableOptions = ref<IOption[]>([]);
    // 列选项
    const columnOptions = ref<IOption[]>([]);
    const conditionOptions = ref<any[]>([]);
    // 决策
    const flowList = ref<any[]>([]);
    const flowRequest = async () => {
      const categoryRes: IPostDecisionListWithCategoryRes = await postDecisionListWithCategory();
      const parentNodes = categoryRes.map((item) => {
        const isDisabled = item.flows?.filter((its) => Number(its?.decisionFlow?.status) === 2);
        return {
          value: item.id,
          label: item.categoryName,
          children: item.flows
            ?.filter((its) => Number(its?.decisionFlow?.status) === 2)
            ?.map((flow) => ({
              value: flow.decisionFlow?.id,
              label: flow.decisionFlow?.flowName
            })),
          leaf: isDisabled?.length ? true : false,
          disabled: isDisabled?.length ? false : true
        };
      });
      flowList.value = parentNodes;
    };
    flowRequest();

    // 决策变量
    const flowVars = ref<any[]>([]);
    const flowVarsRequest = async () => {
      if (!timedExeForm.flowIds || !timedExeForm.flowIds.length) {
        flowVars.value = [];
        return;
      }
      const data = await getDecisionFlowFlowVarsBatch({ flowIds: timedExeForm.flowIds });
      if (data) {
        flowVars.value = data.map((item: any) => {
          return {
            label: item.varLabel || item.varName,
            value: item.varName
          };
        });
      }
    };
    // 表
    const tableRequest = async () => {
      const data: IGetTableListRes = await getTableList();
      if (data) {
        tableOptions.value = data.map((item: string) => {
          return {
            label: item,
            value: item
          };
        });
      } else {
        tableOptions.value = [];
      }
    };
    tableRequest();

    // APP_ID
    const appIdRequest = async () => {
      const data = await getAppList({});
      if (data) {
        appIdOptions.value = data.map((item: any) => {
          return {
            label: item.appName,
            value: item.appId
          };
        });
      } else {
        appIdOptions.value = [];
      }
    };
    appIdRequest();

    // 获取数据表的列
    const columnRequest = async () => {
      if (!timedExeForm.tableName) return;
      const params: IGetTableFieldsReq = {
        tableName: timedExeForm.tableName
      };
      const data: IGetTableFieldsRes = await getTableFields(params);
      if (data) {
        columnOptions.value = data.map((item: any) => {
          return {
            label: item.varLabel ? item.varLabel : item.varName,
            value: item.varName,
            varLabel: item.varLabel ? item.varLabel : item.varName,
            varName: item.varName
          };
        });
      } else {
        columnOptions.value = [];
      }
      // buildConditionOptions(columnOptions.value);
    };

    // const buildConditionOptions = (data: any[]) => {
    //   if (!data) conditionOptions.value = [];
    //   conditionOptions.value = data.map((item: any) => {
    //     return {
    //       label: item.varLabel ? item.varLabel : item.varName,
    //       value: item.varName
    //     };
    //   });
    // };

    // 表单校验-决策
    const flowValidator = (rule: any, value: string, callback: any) => {
      if (!timedExeForm.flowIds || !timedExeForm.flowIds.length) {
        return callback(new Error('请选择决策'));
      }
      callback();
    };
    // 表单校验-cron
    const cronValidator = (rule: any, value: string, callback: any) => {
      if (!timedExeForm.cronExpression) {
        return callback(new Error('请生成cron规则'));
      }
      callback();
    };
    const appIdValidator = (rule: any, value: string, callback: any) => {
      if (!timedExeForm.appId) {
        return callback(new Error('请选择APP_ID'));
      }
      callback();
    };
    const tableNameValidator = (rule: any, value: string, callback: any) => {
      if (!timedExeForm.tableName) {
        return callback(new Error('请选择数据集'));
      }
      callback();
    };
    // 表单校验-映射字段
    const mappingValidator = (rule: any, value: string, callback: any) => {
      if (!timedExeForm.mapping) {
        return callback(new Error('请添加字段映射'));
      }
      const keys = Object.keys(timedExeForm.mapping);
      if (!keys || !keys.length) {
        return callback(new Error('字段映射不可为空，请添加'));
      }
      callback();
    };
    const rules = reactive<any>({
      // appId: [{ required: true, message: '请选择APP_ID', trigger: 'blur' }],
      appId: [{ required: true, message: '请选择APP_ID', validator: appIdValidator }],
      // open: [{ required: true, message: '请打开或关闭开关', trigger: 'blur' }],
      // tableName: [{ required: true, message: '请选择数据集', trigger: 'blur' }],
      tableName: [{ required: true, message: '请选择数据集', validator: tableNameValidator }],
      // cronExpression: [{ required: true, message: '请生成cron规则', trigger: 'blur' }],
      cronExpression: [{ required: true, message: '请生成cron规则', validator: cronValidator }],
      flowIds: [{ required: true, message: '请选择决策', validator: flowValidator, trigger: 'blur' }],
      mapping: [{ required: true, message: '请添加映射字段', validator: mappingValidator, trigger: 'blur' }]
    });

    // 新增请求
    const addRequest = () => {
      const params = {
        ...timedExeForm
      };
      if (params.hasOwnProperty('jobName')) {
        delete params.jobName;
      }
      postJobAdd(params).then(() => {
        emit('close');
      });
    };
    // 修改请求
    const modifyRequest = () => {
      const params = {
        ...timedExeForm
      };
      postJobModify(params).then(() => {
        emit('close');
      });
    };

    // 表单校验
    const formValidate = () => {
      timedExeFormRef.value?.validate((valid: any) => {
        if (valid) {
          // 提交表单
          if (timedExeForm.id) {
            modifyRequest();
          } else {
            addRequest();
          }
        }
      });
    };

    watch(
      [() => timedExeForm.tableName],
      () => {
        if (!modifyFlag) {
          timedExeForm.mapping = {};
        }
        tableNameFlag = false;
        modifyFlag = flowIdsFlag || tableNameFlag;
        columnRequest();
      },
      { deep: true }
    );
    watch(
      [() => timedExeForm.flowIds],
      () => {
        if (!modifyFlag) {
          timedExeForm.mapping = {};
        }
        flowIdsFlag = false;
        modifyFlag = flowIdsFlag || tableNameFlag;
        flowVarsRequest();
      },
      { deep: true }
    );

    expose({
      initData,
      resetData,
      formValidate
    });

    return () => {
      return (
        <div>
          <MciForm ref={timedExeFormRef} data={timedExeForm} rules={rules} label-width={'auto'} label-position={'top'}>
            <MciFormItem label="APP_ID" prop="appId">
              <MciSelect
                vModel={timedExeForm.appId}
                list={appIdOptions.value}
                style={{ width: 'calc(100% - 8px)' }}
                size="default"
              />
            </MciFormItem>
            <MciFormItem label="决策" prop="flowIds">
              <ElTreeSelect
                disabled={!!timedExeForm.id}
                collapse-tags
                collapse-tags-tooltip
                max-collapse-tags={1}
                vModel={timedExeForm.flowIds}
                data={flowList.value}
                style={{ width: 'calc(100% - 8px)' }}
                render-after-expand={false}
                fit-input-width={true}
                show-checkbox={true}
                check-on-click-node
                multiple
                class="treeSelect"
              />
            </MciFormItem>

            <MciFormItem label="数据集" prop="tableName">
              <MciSelect
                disabled={!!timedExeForm.id}
                vModel={timedExeForm.tableName}
                list={tableOptions.value}
                style={{ width: 'calc(100% - 8px)' }}
                size="default"
              />
            </MciFormItem>

            {timedExeForm.tableName && (
              <div class="mt-16">
                <MciFormItem label={'参数映射'} prop="mapping">
                  <FieldMapping
                    ref={fieldMappingRef}
                    disabled={false}
                    column-options={columnOptions.value}
                    variable-options={flowVars.value}
                    mapping={timedExeForm.mapping}
                    is-match={mappingParam.isMatch}
                    onChange={(val: any) => {
                      timedExeForm.mapping = val;
                    }}
                    onMatch={() => (mappingParam.isMatch = false)}
                  />
                </MciFormItem>
              </div>
            )}

            {timedExeForm.tableName && (
              <div>
                <MciFormItem label="执行周期" prop="cronExpression">
                  <Crontab
                    vModel={timedExeForm.cronExpression}
                    style="width: calc(100% - 8px)"
                    onUpdate:modelValue={(val: string) => {
                      timedExeForm.cronExpression = val;
                    }}
                  />
                </MciFormItem>
              </div>
            )}
            {timedExeForm.tableName && (
              <div>
                <MciFormItem label="是否全量扫描" prop="isFullScan">
                  <MciSwitch vModel={timedExeForm.fullScan} active-value={1} inactive-value={0} />
                </MciFormItem>
              </div>
            )}
          </MciForm>
        </div>
      );
    };
  }
});
